import { Http } from '@angular/http';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Stock, StockService } from '../stock.service';

@Component({
  selector: 'app-stock-form',
  templateUrl: './stock-form.component.html',
  styleUrls: ['./stock-form.component.css']
})
export class StockFormComponent implements OnInit {

  stock: Stock = new Stock(0, '', 0, 0, '', []);

  public formModule: FormGroup;

  categories: Array<any> = ['IT', '互联网', '能源', '交通', '医疗', '教育']

  constructor(private routerInfo: ActivatedRoute, private stockService: StockService, private router: Router, public fb: FormBuilder, public http: Http) { }

  ngOnInit() {
    let stockID = this.routerInfo.snapshot.params['id'];

    this.formModule = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      price: ['', [Validators.required, this.priceValidator]],
      desc: [''],
      categories: this.fb.array([
        new FormControl(false),
        new FormControl(false),
        new FormControl(false),
        new FormControl(false),
        new FormControl(false),
        new FormControl(false)
      ], this.categoriesValidator)
    });

    this.stockService.getStock(stockID).subscribe(
      data => {
        this.stock = data;
        this.formModule.reset({
          name:data.name,
          price:data.price,
          desc:data.desc,
          categories:[
            data.categories.indexOf(this.categories[0]) !==-1,
            data.categories.indexOf(this.categories[1]) !==-1,
            data.categories.indexOf(this.categories[2]) !==-1,
            data.categories.indexOf(this.categories[3]) !==-1,
            data.categories.indexOf(this.categories[4]) !==-1,
            data.categories.indexOf(this.categories[5]) !==-1,
          ]
        })
      }
    );
  }

  priceValidator(control: FormControl): any {
    let reg = /^[+]?[\d]+(([\.]{1}[\d]+)|([\d]*))$/;
    if (control.value) {
      return reg.test(control.value) ? null : { "priceError": '股票价格为正整数或小数' }
    }
    return null;
  }
  categoriesValidator(control: FormArray): any {
    return control.controls.some(e => e.value == true) ? null : { 'categoriesEmpty': true }
  }

  cancel() {
    this.router.navigateByUrl('/stock');
  }
  save() {
    let chineseCategories = [];
    let index = 0;
    this.formModule.value.categories.forEach((element, i) => {
      if (element) {
        chineseCategories[index++] = this.categories[i]
      }
    });
    this.formModule.value.categories = chineseCategories;
    this.formModule.value.rating = this.stock.rating;
    console.log(this.formModule.value);
    // this.router.navigateByUrl('/stock');
  }

}
